package com.tucc.hello.leetcode.no1_400.no1_200.no1_20.no11_20.no16;

import java.util.Arrays;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {1, 2, 4, 8, 16, 32, 64, 128};
        int target = 82;
        System.out.println(solution.threeSumClosest(nums, target));
    }

    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int min = Integer.MAX_VALUE;
        int value = 0;
        for (int i = 0; i < nums.length; i++) {
            int k = i + 2;
            for (int j = i + 1; j < nums.length - 1; j++) {
                int abSum = nums[i] + nums[j];
                boolean flagA = false, flagB = false;
                while (k < nums.length && k > j) {
                    int curSum = abSum + nums[k];
                    int dValue = curSum - target;
                    if (dValue == 0) {
                        return target;
                    }
                    int curAbs = Math.abs(curSum - target);
                    if (curAbs < min) {
                        min = curAbs;
                        value = curSum;
                    }
                    if (dValue > 0) {
                        flagA = true;
                        k--;
                    } else {
                        flagB = true;
                        k++;
                    }
                    if(flagA && flagB){
                        break;
                    }
                }
                if (k == nums.length) {
                    k = nums.length - 1;
                }
            }
        }
        return value;
    }
}
